package com.qianbei.common.pay;

import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;

import com.android.volley.Request;
import com.qianbei.R;
import com.qianbei.common.base.ActivityManagers;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.net.view.ToastAlert;

import org.json.JSONObject;

/**
 * 确认完成订单
 *
 * @author gml
 */
@SuppressLint("NewApi")
public class PayDialog extends DialogFragment implements OnClickListener {


    /**
     * 支付 订单ID
     */
    private String order_id = null;

    /**
     * 支付 URL
     */
    private String payUrl;


    private static final int wx = 2;//微信支付方式
    private static final int zfbao = 1;// 支付宝方式

    private static  final String ORDER_ID ="order_id";

    private static  final String PAY_URL ="payUrl";


    public static PayDialog newInstance(String order_id, String url) {
        PayDialog f = new PayDialog();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putString(ORDER_ID, order_id);
        args.putString(PAY_URL, url);
        f.setArguments(args);
        return f;
    }


    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            order_id = getArguments().getString(ORDER_ID);// ("typ");.
            payUrl = getArguments().getString(PAY_URL);
        }
        View v = View.inflate(getActivity(), R.layout.commont_pay_fragment, null);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        v.findViewById(R.id.pay_wx).setOnClickListener(this);
        v.findViewById(R.id.pay_zhifbao).setOnClickListener(this);
        v.findViewById(R.id.pay_all).setOnClickListener(this);
        return v;
    }

    @Override
    public void onClick(View arg0) {

        switch (arg0.getId()) {
            case R.id.pay_wx:
                ConfirmOrder(payUrl, order_id, wx + "");
                dismiss();
                break;
            case R.id.pay_zhifbao:
                ConfirmOrder(payUrl, order_id, zfbao + "");
                dismiss();
                break;
            case R.id.pay_all:
                payCallBack.payFail();
                dismiss();
                break;

          
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black);
//				Theme_Black_NoTitleBar_Fullscreen);
    }




    /**
     * 获取支付码
     * <p/>
     * orderId（订单ID） name:商品名称 totalPrice:订单价格 uuid:用户ID payWay:支付方式（微信：wx 支付宝
     * al）
     */
    private void ConfirmOrder(String url, final String order_id, final String payment_type) {
        ServerControl sc = new ServerControl(Request.Method.POST,
                url, "order_id", order_id, "payment_type", payment_type);

        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    if (payment_type.equals("2")) {

                        weiXinPay(sr.bodyData);
                    } else {
                        zhiFubaoPay(sr.bodyData);
                    }

                }
            }
        };
        new ProgressDialog(getActivity()).startControl(sc);
    }

    /**
     * 支付宝支付方式
     *
     * @param jsonObject
     */
    private void zhiFubaoPay(JSONObject jsonObject) {
        PayService.getInstance().alipayPay(
                jsonObject.optString("order_string")
                        .toString(), new PayService.PayResultListener() {

                    @Override
                    public void payResult(boolean isSuccess) {
                        Log.d("lz", "支付宝支付完成");
                        if (isSuccess) {
//                            new MsgAlert().show("支付成功");
                            new ToastAlert().show(R.string.pay_success,true);
                            if (payCallBack != null) {
                                payCallBack.paySuccess();
                            }
                        } else {
//                            new MsgAlert().show("支付失败");
                            new ToastAlert().show(R.string.pay_fail,false);
                            if (payCallBack != null) {
                                payCallBack.payFail();
                            }
                        }
                    }
                }, ActivityManagers.getCurrentActivity());
    }


    private void weiXinPay(JSONObject jsonObject) {
        PayService.getInstance().wechatPay(
                jsonObject.optJSONObject("order_string"),
                new PayService.PayResultListener() {
                    @Override
                    public void payResult(boolean isSuccess) {
                        Log.d("lz", "微信支付完成");
                        if (isSuccess) {
//                            new MsgAlert().show("支付成功");
                            new ToastAlert().show(R.string.pay_success,true);
                            if (payCallBack != null) {
                                payCallBack.paySuccess();
                            }
                        } else {
                            new ToastAlert().show(R.string.pay_fail,false);
//                            new MsgAlert().show("支付失败");
                            if (payCallBack != null) {
                                payCallBack.payFail();
                            }
                        }
                    }
                }, ActivityManagers.getCurrentActivity());
    }


    private PayCallBack payCallBack;

    public void setPayCallBack(PayCallBack payCallBack) {
        this.payCallBack = payCallBack;
    }

    public interface PayCallBack {
        void paySuccess();

        void payFail();
    }



}
